package com.zk.code.net;

/**
 * Created by zhoukaich on 2018/8/9.
 */
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class UdpClient {
    public static final int MessageReceived = 0x99;
    private int scanPort = 9999;
    public static Channel channel;
    private static void startAndSend(String msg){
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new UdpClientHandler());

        try {
            channel = b.bind(0).sync().channel();
            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8), new InetSocketAddress(NetConfig.HOST, NetConfig.PORT))).sync();
            if (!channel.closeFuture().await(15000)) {
                System.err.println("Search request timed out.");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args){
        startAndSend("你妈妈的啊");
    }
    public static void sendMessage(String msg){
        startAndSend(msg);
        /*try {
            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询?", CharsetUtil.UTF_8), new InetSocketAddress("127.0.0.1", 9999))).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }

    public Channel getChannel(){
        return channel;
    }
    public static UdpClient getInstance(){
        return udpClient.INSTANCE;
    }

    private static final class udpClient{
        static final UdpClient INSTANCE = new UdpClient();
    }





}

